import { _decorator, Component, EditBox, instantiate, Node, Prefab, ScrollView, UITransform } from 'cc';

const { ccclass, property } = _decorator;
import Recorder from 'js-audio-recorder'
import { UIManager } from '../common/UIManager';
import { PrefabEnum } from '../common/PrefabEnum';
import { ChatItem } from './ChatItem';
import { UIHeader } from '../common/UIHeader';
import { EventManager } from '../event/EventManager';

@ccclass('AIAsistant')
export class AIAsistant extends Component {
    @property(UIHeader)
    uiHeader: UIHeader

    @property(Node)
    recordBtn: Node
    @property(Node)
    send: Node
    @property(EditBox)
    editBox: EditBox
    @property(ScrollView)
    scrollView: ScrollView
    @property(Node)
    content: Node
    @property(Prefab)
    chatItem: Prefab
    @property(Prefab)
    chatItemSelf: Prefab
    @property(Prefab)
    recording: Prefab

    private recorder
    start() {
        this.uiHeader.setData(`AI助手`)
        EventManager.instance.on(`AI助手close`, this.onClose, this)


        this.init()

        this.recordBtn.on(Node.EventType.TOUCH_START, this.onTouchStart, this)
        this.recordBtn.on(Node.EventType.TOUCH_END, this.onTouchEnd, this)
        this.send.on(Node.EventType.TOUCH_END, this.onSend, this)
    }

    init() {
        this.recorder = new Recorder({
            sampleBits: 16,                 // 采样位数，支持 8 或 16，默认是16
            sampleRate: 16000,              // 采样率，支持 11025、16000、22050、24000、44100、48000，根据浏览器默认值，我的chrome是48000
            numChannels: 1,
        })
        Recorder.getPermission().then(() => {
            console.log('给权限了')

        }, (error) => {

            UIManager.instance.modal('提示', '请授权录音', false)
        })
    }

    onTouchStart() {
        Recorder.getPermission().then(() => {
            console.log('给权限了')
            this.recorder.start() // 开始录音
            UIManager.instance.openUI(PrefabEnum.Recording)
        }, (error) => {

            UIManager.instance.modal('提示', '请授权录音', false)
        })

    }

    onTouchEnd() {
        this.recorder.stop();
        UIManager.instance.closeUI(PrefabEnum.Recording)

        this.uploadRecord()
        // this.recorder.downloadWAV()
    }

    async onSend() {
        let str = this.editBox.string
        if (!str) {
            UIManager.instance.tip('请输入内容')
            return
        }

        let random = Math.random()
        let node: Node
        if (random < 0.5) {
            node = instantiate(this.chatItemSelf)
        } else {
            node = instantiate(this.chatItem)
        }
        this.content.addChild(node)
        node.getComponent(ChatItem).setData(str)

        this.editBox.string = ''

        let scrollHeight = this.scrollView.getComponent(UITransform).height
        let contentHeight = this.content.getComponent(UITransform).height
        
        if (contentHeight >= scrollHeight) {
            this.scrollView.scrollToBottom()
        }

    }

    async uploadRecord() {
        if (this.recorder == null || this.recorder.duration === 0) {
            return
        }
        this.recorder.pause() // 暂停录音

        console.log('上传录音')// 上传录音

        const formData = new FormData()
        const blob = this.recorder.getWAVBlob()// 获取wav格式音频数据
        // 此处获取到blob对象后需要设置fileName满足当前项目上传需求，其它项目可直接传把blob作为file塞入formData
        const newbolb = new Blob([blob], { type: 'audio/wav' })
        const fileOfBlob = new File([newbolb], new Date().getTime() + '.wav')
        formData.append('file', fileOfBlob)

        await UIManager.instance.showLoading()

        try {
            let response = await fetch('https://bc.gamegold.xin/app/work/sample', {
                method: 'POST',

                body: formData,
            })

            UIManager.instance.closeLoading()

            let data = await response.json()
            console.log(data)
            let msg = JSON.parse(data.msg)

            let result = msg.result[0]

            this.editBox.string = result
        } catch (error) {
            console.log(error)
            UIManager.instance.closeLoading()
        }




    }


    onClose() {
        UIManager.instance.closeUI(PrefabEnum.AIAsistant)
    }
}


